package com.ruoyi.weixin.util;

import com.ruoyi.common.utils.DateUtils;
import net.sf.json.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.text.ParseException;


public class weixinTest {




	/**
	 * 设置行业
	 * @param wxu
	 * @param at
	 */
	public static void set(WeixinUtil wxu, AccessToken at) {

		/*{
		    "industry_id1":"1",
		    "industry_id2":"4"
		}*/
		JSONObject json = new JSONObject();

        json.put("industry_id1", "2");
        json.put("industry_id2", "22");

		String retVal = wxu.send(at.getToken(), json.toString() );
    	System.out.println(retVal);
    	JSONObject jsonObject = JSONObject.fromObject(retVal);
        // 判断菜单创建结果
        if ("0".equals(jsonObject.getString("errcode"))) {
     	   System.out.println("设置行业成功！");
        }else  {
     	   System.out.println("设置行业失败，错误码：" + retVal);
        }
	}

	/**
	 * 获取设置的行业信息
	 * @param wxu
	 * @param at
	 */
	public static void get(WeixinUtil wxu, AccessToken at) {

		String retVal = wxu.get(at.getToken());
    	System.out.println(retVal);
	}

	/**
	 * 发送模板信息
	 * @param wxu
	 * @param at
	 */
/*	public static void sendTempMsg(WeixinUtil wxu, AccessToken at) {
		String openId = "\"otOql5nAIjEvRInnKOfE81NYxOmg\"";
    	String param = "{\"touser\":"+openId+",\"template_id\": \"XDOsGgp8YMQ6SvN1HqS6pJR1GPzjvOnH8fuQXbWHbMI\"" +
    					",\"url\": \"\",\"data\": {\"first\": {\"value\":\"您好，有新的留言内容\",\"color\":\"#173177\"}" +
    					",\"keyword1\":{\"value\":\"系统\",\"color\":\"#173177\"},\"keyword2\": {\"value\":\"有故障信息：001工位出现了机器故障，请及时处理。异常原因：缺少零件\",\"color\":\"#173177\"}" +
    					",\"keyword3\":{\"value\":\"2020-07-01 17:19:10\",\"color\":\"#173177\"}" +
    					",\"remark\": {\"value\":\"希望您查看\",\"color\":\"#173177\"}}}";
    	String retVal = wxu.sendMesByTemp(at.getToken(), param);
    	System.out.println(retVal);
	}*/

	public static void sendTempMsg(WeixinUtil wxu, AccessToken at) {

		String openId = "oLbe15r8jZKRFEjYyVxnWG9XzXCg";
		String template_id = "cz8I234IfedAau4FGD6lf1dwy75wRpuuet8kV6djYVI";
		String url = "https://www.baidu.com/";
		//当前时间
		String format = DateUtils.dateTimeNow("yyyy年MM月dd日 HH:mm:ss");


		JSONObject jsonObject = new JSONObject();
		jsonObject.put ( "touser",openId );
		jsonObject.put ( "template_id",template_id);
		jsonObject.put ( "url" , url );

		JSONObject data = new JSONObject() ;

		JSONObject first = new JSONObject();
		first.put ( "value" , "亲爱的欧小进同学，本次作业评价如下" );
		first.put ( "color","#173177" );

		JSONObject keyword1 = new JSONObject();
		keyword1.put ( "value" , "经典文献" );
		keyword1.put ( "color","#173177" );

		JSONObject keyword2 = new JSONObject();
		keyword2.put ( "value" , "作业标题" );
		keyword2.put( "color","#173177" );

		JSONObject keyword3 = new JSONObject();
		keyword3.put ( "value" , "教师评分" );
		keyword3.put( "color","#173177" );

		JSONObject keyword4 = new JSONObject();
		keyword4.put ( "value" , format );
		keyword4.put( "color","#173177" );

		JSONObject remark = new JSONObject();
		remark.put ( "value" , "点击查看教师的详细评论。" );
		remark.put ( "color", "#173177" );

		data.put("first" ,first ) ;
		data.put("keyword1" , keyword1) ;
		data.put("keyword2" , keyword2);
		data.put("keyword3" , keyword3) ;
		data.put("keyword4" , keyword4) ;
		data.put( "remark" , remark ) ;
		jsonObject.put ( "data" , data);

		String retVal = wxu.sendMesByTemp(at.getToken(), jsonObject.toString());
		System.out.println(retVal);
	}

	/**
	 * 上传素材
	 * @param at 获取token
	 * @param path 文件路径
	 * @param type 文件类型
	 */
	public static String upload(AccessToken at, String path, String type) {
		String retVal = "";
		//File file = new File(path);
		File file = new File("E://image//4.jpg");
		//地址
		String upload_url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
		upload_url = upload_url.replace("ACCESS_TOKEN", at.getToken()).replace("TYPE", type);

		 URL url;
		try {
			url = new URL(upload_url);
		 //强转为安全链接
         HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
         //设置连接信息
         httpUrlConn.setDoOutput(true);
         httpUrlConn.setDoInput(true);
         httpUrlConn.setUseCaches(false);
         //设置请求头信息
         httpUrlConn.setRequestProperty("Connection", "keep-alive");
         httpUrlConn.setRequestProperty("Charset", "utf-8");
         //数据的边界
         String boundary = "-----"+System.currentTimeMillis();
         httpUrlConn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
         //获取输出流
         OutputStream outputStream = httpUrlConn.getOutputStream();
         //创建文件输入流
         InputStream fis = new FileInputStream(file);
         BufferedInputStream is = new BufferedInputStream(fis);
         //第一部分：头部信息
         	//准备头部信息
         	StringBuilder sb = new StringBuilder();
         	sb.append("--");
         	sb.append(boundary);
         	sb.append("\r\n");
         	sb.append("Content-Disposition:form-data;name=\"media\";filename=\""+file.getName()+"\"\r\n");
         	sb.append("Content-Type:application/octet-stream\r\n\r\n");
         	outputStream.write(sb.toString().getBytes("UTF-8"));
         //第二部分：文件内容
            byte[] b = new byte[1024];
            int len;
            while((len = is.read(b)) != -1) {
            	outputStream.write(b, 0, len);
            }
         //第三部分：尾部信息
            String foot = "\r\n--"+boundary+"--\r\n";
            outputStream.write(foot.getBytes());
            outputStream.flush();
            outputStream.close();  
         //读取数据
            StringBuilder sBuilder = new StringBuilder();
            InputStream inputStream = httpUrlConn.getInputStream();  
            while((len = inputStream.read(b)) != -1) {
            	sBuilder.append(new String(b, 0, len));
            }
            retVal = sBuilder.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retVal; 
		//{"type":"image","media_id":"mGEgwT-csFH4V4NtxXBMXN7t2JT72b23LV17A5wgYCL7UX7VuqGR_u0KerGsKRcI","created_at":1593669494,"item":[]}--返回结果
	}
	
	/*下载上传的素材：
	https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=mGEgwT-csFH4V4NtxXBMXN7t2JT72b23LV17A5wgYCL7UX7VuqGR_u0KerGsKRcI
	34_zog-A4aURI3WwkY7_sk-HYEnq9595TQx_1V8ptx-PrOPbYgrz2Nru8eSWSIdUUZgFzfWoC3kvxfUbTOhg2PWT-UtfxVnyyhcWgZC7xlnVYBAiASX6jGaDJS89RjPRD0prudpmQmxo3bqXOORRIAfAGADUM*/
	
	/**
	 * 根据用户Openid获取用户信息
	 * @param wxu
	 * @param at
	 */
	public static void getUser(WeixinUtil wxu, AccessToken at) {
		
		String openId = "olDESw4FNmZUpFRfrVA-wWsPY-CU";
		String retVal = wxu.queryUserByOPENID(openId, at.getToken());
    	System.out.println(retVal);
	}
}
